package com.hrbxlh.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.hrbxlh.actionImpl.RelStuClassActionImpl;
import com.hrbxlh.util.ConfigFileUtil;
import com.hrbxlh.util.FileUpload;
import com.hrbxlh.util.PubMethods;
import com.hrbxlh.util.SessionValues;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hrbxlh.actionImpl.CourseActionImpl;
import com.hrbxlh.actionImpl.MyCourseActionImpl;
import com.hrbxlh.actionImpl.QuestionActionImpl;


/**
 * -------------------------------------------------------
 * Copyright (c) 2017, 鑫联华信息科技股份有限公司
 * All rights reserved.
 * FileName：SourceAction.java
 * Description：题库action类
 * History：
 * Date           Author               Desc
 * 2017.4.20		  sy                   建立
 * -------------------------------------------------------
 */

@Controller
public class QuestionAction {

	@Autowired
	@Qualifier("questionActionImpl")
	private QuestionActionImpl questionActionImpl;

	@Autowired
	@Qualifier("courseActionImpl")
	private CourseActionImpl courseActionImpl;

	@Autowired
	@Qualifier("myCourseActionImpl")
	private MyCourseActionImpl myCourseActionImpl;

	@Autowired
	@Qualifier("relStuClassActionImpl")
	private RelStuClassActionImpl relStuClassActionImpl;

	//日志信息
	Logger logger = Logger.getLogger(QuestionAction.class.getName());

	/**
	 * @param
	 * @return  题库列表页面。进页面，翻页，条件查询都是这个。
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getAllQuestionList", method = RequestMethod.GET)
	public ModelAndView getAllQuestionList(String jsonStr, HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//返回字符串
		String reJsonStr = "";
		//存放页面
		String pageName = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();

		try {
			//模拟参数开始
//			Map<String, Object> mapUse = new HashMap<String, Object>();
//			mapUse.put("pageNow", 1);
//			mapUse.put("pageSize", 10);
//			jsonStr = mapper.writeValueAsString(mapUse);
			//模拟参数结束
			logger.info("题库列表页面的参数为："+jsonStr);
			//获取页面参数值
			Map<String, Object> preParamMap = mapper.readValue(jsonStr, returnMap.getClass());
			//获取题库列表信息
			Map<String, Object> resultAllMap = questionActionImpl.getAllQuestionList(preParamMap,session,request);
			if(String.valueOf(resultAllMap.get("flag")).equals("success")){
				if(preParamMap.get("courseId")!=null||preParamMap.get("courseId")!=null){
					//搜素框赋值对象
					Map<String,Object> searchObejct = new HashMap<String,Object>();
					searchObejct.put("courseId", preParamMap.get("courseId"));
					resultMap.put("searchObejct", searchObejct);
				}

				//查询当前人的消息
				/*List<Map<String, Object>> noticeList = courseActionImpl.getMyNotice(request);
				resultMap.put("noticeList", noticeList);*/
//				String a = "%3Cdiv%20style%3D%22font-size%3A30px%3B%22%3E%u8428%u62C9%u4E01%3C/div%3E";
				//返回值
				resultMap.put("questionList", resultAllMap.get("questionList"));
				resultMap.put("courseListAll", resultAllMap.get("courseListAll"));
				resultMap.put("courseList", resultAllMap.get("courseList"));
				resultMap.put("stuorteaId", resultAllMap.get("stuorteaId"));
				resultMap.put("totalPage", resultAllMap.get("totalPage"));
				resultMap.put("pageNow", resultAllMap.get("pageNow"));
				resultMap.put("pageSize", preParamMap.get("pageSize"));
//				resultMap.put("a", a);
				//人员列表页面名称
				pageName = "pc/questionList";
			}else{
				resultMap.put("pageNow", 1);
				resultMap.put("pageSize", 10);
				resultMap.put("totalPage", 0);
				resultMap.put("errMsg", resultAllMap.get("errMsg"));
				pageName = "pc/questionList";
			}

		} catch (Exception e) {
			resultMap.put("errMsg", "跳转页面失败");
			e.printStackTrace();
			logger.error("跳转题库列表页面出现异常", e);
			pageName = "public/pageerror";
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			returnMap.put("result", reJsonStr);
			logger.info("返回的  :" + reJsonStr);
		}
		return new ModelAndView(pageName, returnMap);
	}

	/**
	 * @param
	 * @return  题库列表页面。进页面，翻页，条件查询都是这个。
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getAllQuestionListByPost", method = RequestMethod.POST)
	public void getAllQuestionListByPost(String jsonStr, HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//返回字符串
		String reJsonStr = "";
		//存放页面
		String pageName = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();

		try {
			logger.info("题库列表页面的参数为："+jsonStr);
			//获取页面参数值
			Map<String, Object> preParamMap = mapper.readValue(jsonStr, returnMap.getClass());
			//获取题库列表信息
			Map<String, Object> resultAllMap = questionActionImpl.getAllQuestionList(preParamMap,session,request);
			if(preParamMap.get("courseId")!=null||preParamMap.get("courseId")!=null){
				//搜素框赋值对象
				Map<String,Object> searchObejct = new HashMap<String,Object>();
				searchObejct.put("courseId", preParamMap.get("courseId"));
				resultMap.put("searchObejct", searchObejct);
			}

			//返回值
			resultMap.put("questionList", resultAllMap.get("questionList"));
			resultMap.put("courseList", resultAllMap.get("courseList"));
			resultMap.put("stuorteaId", resultAllMap.get("stuorteaId"));
			resultMap.put("totalPage", resultAllMap.get("totalPage"));
			resultMap.put("pageNow", resultAllMap.get("pageNow"));
			resultMap.put("pageSize", preParamMap.get("pageSize"));
			resultMap.put("result", "success");
			resultMap.put("failMsg", "");
		} catch (Exception e) {
			resultMap.put("result", "fail");
			resultMap.put("failMsg", "跳转页面失败");
			e.printStackTrace();
			logger.error("跳转题库列表页面出现异常", e);
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			logger.info("题库列表页面的返回结果为："+resultMap);
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter write = response.getWriter();
			write.println(reJsonStr);
			write.flush();
		}

	}

	/**
	 * @param request
	 * @param response
	 * @return  添加问题表单提交。
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/addQuestion", method = RequestMethod.POST)
	public void addQuestion(String jsonStr, HttpServletRequest request, HttpServletResponse response) throws IOException {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//返回字符串
		String reJsonStr = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//成功失败标识
		String resultMark = "fail";
		try {
			logger.info("添加问题表单提交的参数为："+jsonStr);
			//获取参数值
			Map<String,Object> paramMap = mapper.readValue(jsonStr, resultMap.getClass());
			//成绩设置。
			Map<String,Object> returnMap = questionActionImpl.addQuestion(paramMap);
			boolean resultFlag = (Boolean) returnMap.get("flag");
			resultMark = (resultFlag) ? "success" : "fail";
			resultMap.put("result", resultMark);
			resultMap.put("msg", returnMap.get("msg"));
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("添加问题出现异常", e);
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			logger.info("添加问题表单提交的返回结果为："+reJsonStr);
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter write = response.getWriter();
			write.println(reJsonStr);
			write.flush();
		}
	}

	/**
	 * @param request
	 * @param response
	 * @return  删除题库,传回题库id集合。List<String>形式   jsonStr = ["1","2","3"...]
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/delQuestions", method = RequestMethod.POST)
	public void delQuestions(String jsonStr, HttpServletRequest request, HttpServletResponse response) throws IOException {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//返回字符串
		String reJsonStr = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		String errorMsg = "";
		//成功失败标识
		String resultMark = "fail";
		//用于转换参数
		List<String> list = new ArrayList<String>();
		try {
			/*模拟参数开始*/
			//List<Integer> listUse = new ArrayList<Integer>();
			//listUse.add(2);
			//listUse.add(3);
			//jsonStr = mapper.writeValueAsString(listUse);
			/*模拟参数结束*/
			logger.info("删除题库的参数为："+jsonStr);
			//获取参数值
			List<String> paramList = mapper.readValue(jsonStr, list.getClass());
			//删除人员
			boolean flag = questionActionImpl.delQuestions(paramList);
			resultMark = (flag == true) ? "success" : "fail";
			resultMap.put("result", resultMark);
			if(resultMark.equals("fail")){
				errorMsg = "删除试题失败";
			}
			resultMap.put("errorMsg", errorMsg);
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("errorMsg", "删除题库出现异常");
			logger.error("删除题库出现异常", e);
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			logger.info("删除题库的返回结果为："+resultMap);
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter write = response.getWriter();
			write.println(reJsonStr);
			write.flush();
		}
	}

	/**
	 * @param request
	 * @param response
	 * @return  教师批阅ajax请求(前台传课程号，学生id),判断是否设置成绩等级
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "isSetOnlineExamGrade", method = RequestMethod.POST)
	public void isSetOnlineExamGrade(String jsonStr, HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//成功失败标识
		String resultMark = "fail";
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {
			logger.info("教师批阅ajax请求(前台传课程号，学生id),判断是否设置成绩等级的参数为："+jsonStr);
			//获取参数值
			Map<String,Object> paramMap = mapper.readValue(jsonStr, resultMap.getClass());
			//通过课程id和学号查询当前课程的试题
			Map<String,Object> finalMap = questionActionImpl.isSetOnlineExamGrade(paramMap,session,request);
			resultMap.put("result", finalMap.get("result"));
			resultMap.put("failMsg", finalMap.get("errMsg"));


		} catch (Exception e) {
			e.printStackTrace();
			logger.error("教师批阅ajax请求(前台传课程号，学生id),判断是否设置成绩等级出现异常", e);

		} finally {
			logger.info("教师批阅ajax请求(前台传课程号，学生id),判断是否设置成绩等级的返回结果为："+resultMap);
			PubMethods.postMed(response,mapper,resultMap);

		}

	}

	/**
	 * 导入题
	 * @param file
	 * @param response
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/imQuestion", method=RequestMethod.POST)
	public void imQuestion(@RequestParam("file") CommonsMultipartFile file, HttpServletResponse response, HttpServletRequest request) throws Exception {
		String fileName =  file.getOriginalFilename();
		ObjectMapper mapper = new ObjectMapper();
		Map<String,Object> map = new HashMap<String,Object>();
		Map<String,Object> returnMap = new HashMap<String, Object>();
		try{
			logger.info("导入题的参数file为："+file);
			//获取文件后缀
			String allFileName=file.getName();
			String prefix=fileName.substring(fileName.lastIndexOf(".")+1);
			if(!prefix.equals("xls")){
				returnMap.put("msg","fail");
				returnMap.put("errMsg","请将文件改为excel2003版");
				return;
			}
			String path = request.getSession().getServletContext().getRealPath("/upload/" + fileName);// 存放位置
			File destFile = new File(path);
			String file1 = String.valueOf(destFile);
			FileUtils.copyInputStreamToFile(file.getInputStream(), destFile);// 复制临时文件到指定目录下
			returnMap = questionActionImpl.imQuestion(file1,request);
			if(String.valueOf(returnMap.get("errMsg")).equals("null")||returnMap.get("errMsg")==null||String.valueOf(returnMap.get("errMsg")).equals("")){
				returnMap.put("errMsg","导入模板异常，请重新上传");
			}
			//将临时存到文件删除
			PubMethods.delTempFile(fileName);

		}catch(Exception e){
			e.printStackTrace();
			map.put("errMsg", "导入题失败");
			e.printStackTrace();
			logger.error("导入题失败", e);
		}finally{
			logger.info("导入题的返回结果为："+returnMap);
			PubMethods.postMed(response,mapper,returnMap);

		}
	}

	/**
	 * @param request
	 * @param response
	 * @return  查询所需要生成的试题题库中是否存在
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getQuestionsByExcel", method = RequestMethod.POST)
	public void getQuestionsByExcel(String jsonStr, HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//返回字符串
		String reJsonStr = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//成功失败标识
		String resultMark = "fail";
		//用于转换参数
		List<String> list = new ArrayList<String>();
		try {
			/*模拟参数开始*/
			//List<Integer> listUse = new ArrayList<Integer>();
			//listUse.add(2);
			//listUse.add(3);
			//jsonStr = mapper.writeValueAsString(listUse);
			/*模拟参数结束*/
			logger.info("查询所需要生成的试题题库中是否存在参数为："+jsonStr);
			//获取参数值
			Map<String,Object> paramMap = mapper.readValue(jsonStr, returnMap.getClass());
			//查询所选试题类型题库中是否存在
			resultMap = questionActionImpl.getQuestionsByExcel(paramMap,session,request);

		} catch (Exception e) {
			e.printStackTrace();
			logger.error("查询所需要生成的试题题库中是否存在出现异常", e);
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			logger.info("查询所需要生成的试题题库中是否存在参数为："+resultMap);
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter write = response.getWriter();
			write.println(reJsonStr);
			write.flush();
		}
	}

	//#########################################2.0####################################################//

	/**
	 * @param request
	 * @param response
	 * @return  在线预览
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/onlineGetQuestions", method = RequestMethod.POST)
	public void onlineGetQuestions(String jsonStr, HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//返回字符串
		String reJsonStr = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//成功失败标识
		String resultMark = "fail";
		//用于转换参数
		//存放结果值
		Map<String,Object> paraMap = new HashMap<String,Object>();
		try {
			/*模拟参数开始*/
			//List<Integer> listUse = new ArrayList<Integer>();
			//listUse.add(2);
			//listUse.add(3);
			//jsonStr = mapper.writeValueAsString(listUse);
			/*模拟参数结束*/
			logger.info("在线预览参数为："+jsonStr);
			//获取参数值
			Map<String,Object> paramMap = mapper.readValue(jsonStr, returnMap.getClass());
			//查询所选试题
			resultMap = questionActionImpl.getAllQuestionListExcel(paramMap,request);
			resultMap.put("paramMap", paramMap);
			resultMap.put("flag", true);

		} catch (Exception e) {
			resultMap.put("flag", false);
			e.printStackTrace();
			logger.error("在线预览存在出现异常", e);
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			logger.info("在线预览参数为："+resultMap);
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter write = response.getWriter();
			write.println(reJsonStr);
			write.flush();
		}
	}

	/**
	 * param:mark 1添加  2修改  onlinequestionId试卷主键id  添加时给我0修改时给我正常主键
	 * randomMark 1重新随机生成试题（修改时记录数据库）  2不重新随机生成试题（修改时记录数据库）
	 * @return  在线预览试题表单提交。(保存试卷)
	 * 20180509改：教师在同一课程上可以生成多张试卷
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/addOnlineQuestion", method = RequestMethod.POST)
	public void addOnlineQuestion(String jsonStr, HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//返回字符串
		String reJsonStr = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//成功失败标识
		String resultMark = "fail";
		try {
			logger.info("在线预览试题表单提交的参数为："+jsonStr);
			//获取参数值
			Map<String,Object> paramMap = mapper.readValue(jsonStr, resultMap.getClass());
			//在线预览表单提交。
			Map<String ,Object> returnMap = questionActionImpl.addOnlineQuestion(paramMap,request);
			boolean resultFlag = (Boolean)returnMap.get("flag");
			resultMark = (resultFlag) ? "success" : "fail";
			resultMap.put("result", resultMark);
			resultMap.put("errorMsg", returnMap.get("str"));
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("在线预览试题表单提交出现异常", e);
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			logger.info("在线预览试题表单提交的返回结果为："+resultMap);
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter write = response.getWriter();
			write.println(reJsonStr);
			write.flush();
		}
	}

	/**
	 * description:修改试卷获取试卷基本信息
	 * @param onlinequestionId
	 * @return  获取试卷基本信息
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getOnlineById", method = RequestMethod.POST)
	public void getOnlineById(String jsonStr, HttpServletResponse response) throws IOException {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//存放结果值
		Map<String, Object> resultMap = new HashMap<String, Object>();

		try {
			//获取页面参数值
			Map<String, Object> preParamMap = mapper.readValue(jsonStr, returnMap.getClass());
			//通过学生获取此学生所属课程
			Map<String, Object> onlineMap = questionActionImpl.getOnlineById(preParamMap);
			resultMap.put("onlineMap", onlineMap);
			String[] keysArray = {"tomcatUrl", "project_name","server_address"};
			Map<String, Object> urlmap = ConfigFileUtil.getFileMessage("UtilFile.properties", keysArray);
			//判断文件夹存不存在,不存在就创建
			String url = String.valueOf(urlmap.get("server_address"))+String.valueOf(urlmap.get("project_name"))+"upload/question"+"/";
			resultMap.put("url",url);
		} catch (Exception e) {
			resultMap.put("errMsg", "获取试卷基本信息出现异常");
			e.printStackTrace();
			logger.error("获取试卷基本信息出现异常", e);
		} finally {
			PubMethods.postMed(response, mapper, resultMap);
		}

	}

	/**
	 * @param （学号）
	 * @return  该学生的当前所属的所有课程
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getAllStuCourse", method = RequestMethod.POST)
	public void getAllStuCourse(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//返回字符串
		String reJsonStr = "";
		//存放页面
		String pageName = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(MemberAction.class.getName());
		try {
			//获取页面参数值
			Map<String, Object> preParamMap = new HashMap<String,Object>();
			//获取当前登陆人的学号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
			String stuorteaId = String.valueOf(sessionMap.get("stuorteaId")) ;
			preParamMap.put("stuorteaId", stuorteaId);
			//通过学生获取此学生所属课程
			List<Map<String,Object>> courseList = myCourseActionImpl.getStuListCourse(preParamMap);
			resultMap.put("courseList", courseList);
			logger.info("学生进入在线考试列表（课程）页返回结果"+resultMap);
			resultMap.put("result", "success");
			resultMap.put("failMsg", "");
		} catch (Exception e) {
			resultMap.put("result", "fail");
			resultMap.put("failMsg", "跳转页面失败");
			e.printStackTrace();
			logger.error("该学生的当前所属的所有课程出现异常", e);

		} finally {
			PubMethods.postMed(response,mapper,resultMap);
		}
	}

	/**
	 * @param request
	 * @param response
	 * @return  学生在线考试保存提交
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/stuOnlineSubmitExam", method = RequestMethod.POST)
	public void stuOnlineSubmitExam(String jsonStr, HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//返回字符串
		String reJsonStr = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();

		try {
			logger.info("学生在线考试保存提交的参数为："+jsonStr);
			//获取参数值
			Map<String,Object> param = mapper.readValue(jsonStr, resultMap.getClass());
			//将学生答案插入到数据库
			Map<String,Object> returnMap = questionActionImpl.addStuAnswerQuestion(param,session,request);
			resultMap.put("flag", returnMap.get("flag"));
			resultMap.put("msg", returnMap.get("msg"));

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(" 学生在线考试保存提交出现异常", e);
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			logger.info("学生在线考试保存提交的结果为："+reJsonStr);
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter write = response.getWriter();
			write.println(reJsonStr);
			write.flush();
		}
	}

	/**
	 * @param request
	 * @param response
	 * @return  学生在线考试自动保存
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/stuOnlineAutomaticSaveExam", method = RequestMethod.POST)
	public void stuOnlineAutomaticSaveExam(String jsonStr, HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//返回字符串
		String reJsonStr = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();

		try {
			logger.info("学生在线考试自动保存的参数为："+jsonStr);
			//获取参数值
			Map<String,Object> param = mapper.readValue(jsonStr, resultMap.getClass());
			//将学生答案插入到数据库
			Map<String,Object> returnMap = questionActionImpl.stuOnlineAutomaticSaveExam(param,session,request);
			resultMap.put("result", returnMap.get("result"));
			resultMap.put("failMsg", returnMap.get("msg"));

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(" 学生在线考试自动保存出现异常", e);
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			logger.info("学生在线考试自动保存的结果为："+reJsonStr);
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter write = response.getWriter();
			write.println(reJsonStr);
			write.flush();
		}
	}

	/**
	 * @param request
	 * @param response
	 * @return  学生在线考试ajax请求试题(前台传课程号)
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/stuOnlineExam", method = RequestMethod.POST)
	public void stuOnlineExam(String jsonStr, HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//返回字符串
		String reJsonStr = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//成功失败标识
		String resultMark = "fail";
		try {
			logger.info("学生在线考试ajax请求试题(前台传课程号)的参数为："+jsonStr);
			//获取参数值
			Map<String,Object> paramMap = mapper.readValue(jsonStr, resultMap.getClass());
			if(paramMap.get("courseId")!=null||paramMap.get("courseId")!=null){
				//搜素框赋值对象
				Map<String,Object> searchObejct = new HashMap<String,Object>();
				searchObejct.put("courseId", paramMap.get("courseId"));
				resultMap.put("searchObejct", searchObejct);
			}
			//通过课程id和当前登陆人所属老师的工号查询当前课程的试题
			Map<String,Object> returnMap = questionActionImpl.getOnlineQuestion(paramMap,session,request);
			resultMap.put("questonMap", returnMap.get("questonMap"));
			resultMap.put("courseList", returnMap.get("courseList"));
			resultMap.put("mincha",returnMap.get("mincha"));
			resultMap.put("flag", returnMap.get("flag"));
			resultMap.put("errMsg", returnMap.get("errMsg"));

		} catch (Exception e) {
			resultMap.put("errMsg", "学生在线考试ajax请求试题(前台传课程号)出现异常");
			e.printStackTrace();
			logger.error("学生在线考试ajax请求试题(前台传课程号)出现异常", e);
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			logger.info("学生在线考试ajax请求试题(前台传课程号)的参数为："+resultMap);
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter write = response.getWriter();
			write.println(reJsonStr);
			write.flush();
		}
	}



	/**在线批阅列表获取当前登陆人所属学生在线考试列表
	 * @param （工号）
	 * @return  该教师的当前所属的所有班级学生考试情况
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getAllStuExamList", method = RequestMethod.POST)
	public void getAllStuExamList(String jsonStr,HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//返回字符串
		String reJsonStr = "";
		//存放页面
		String pageName = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		try {
			//模拟参数开始
//			Map<String, Object> mapUse = new HashMap<String, Object>();
//			mapUse.put("pageNow", 1);
//			mapUse.put("pageSize", 10);
//			jsonStr = mapper.writeValueAsString(mapUse);
			//模拟参数结束
			logger.info("获取当前登陆人所属学生在线考试列表（工号）的参数为："+jsonStr);
			//搜素框赋值对象
			Map<String,Object> searchObejct = new HashMap<String,Object>();
			//获取页面参数值
			Map<String, Object> preParamMap = mapper.readValue(jsonStr, resultMap.getClass());
			if(preParamMap.get("courseId")!=null||preParamMap.get("courseId")!=null){
				searchObejct.put("courseId", preParamMap.get("courseId"));
			}if(preParamMap.get("state")!=null||preParamMap.get("state")!=null){
				searchObejct.put("state", preParamMap.get("state"));
			}if(preParamMap.get("classId")!=null||preParamMap.get("classId")!=null){
				searchObejct.put("classId", preParamMap.get("classId"));
			}
			resultMap.put("searchObejct", searchObejct);
			//该教师的当前所属的所有班级学生考试情况
			Map<String,Object> findMap = questionActionImpl.getAllStuExamList(preParamMap,session,request);
			resultMap.put("memList", findMap.get("memList"));
			resultMap.put("courseList", findMap.get("courseList"));
			resultMap.put("classList", findMap.get("classList"));
			resultMap.put("totalPage", findMap.get("totalPage"));
			resultMap.put("pageNow", findMap.get("pageNow"));
			resultMap.put("result", "success");
			resultMap.put("failMsg", "");

		} catch (Exception e) {
			resultMap.put("result", "fail");
			resultMap.put("failMsg", "跳转页面失败");
			e.printStackTrace();
			logger.error("在线批阅列表获取当前登陆人所属学生在线考试列表出现异常", e);

		} finally {
			logger.info("在线批阅列表获取当前登陆人所属学生在线考试列表的参数为："+resultMap);
			PubMethods.postMed(response,mapper,resultMap);
		}

	}

	/**
	 * @param request
	 * @param response
	 * @return  教师批阅ajax请求(前台传课程号，学生id)
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/markOnlineExam", method = RequestMethod.POST)
	public void markOnlineExam(String jsonStr, HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//返回字符串
		String reJsonStr = "";
		//存放页面
		String pageName = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//成功失败标识
		String resultMark = "fail";
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {
			logger.info("教师批阅ajax请求(前台传课程号，学生id)的参数为："+jsonStr);
			//获取参数值
			Map<String,Object> paramMap = mapper.readValue(jsonStr, resultMap.getClass());
			//通过课程id和学号查询当前课程的试题
			Map<String,Object> finalMap = questionActionImpl.getMarkStuQuestion(paramMap,session,request);
			resultMap.put("question", finalMap.get("question"));
			resultMap.put("errMsg", finalMap.get("errMsg"));


		} catch (Exception e) {
			e.printStackTrace();
			logger.error(" 教师批阅ajax请求(前台传课程号，学生id)出现异常", e);

		} finally {
			logger.info("教师批阅ajax请求(前台传课程号，学生id)的返回结果为："+resultMap);
			PubMethods.postMed(response,mapper,resultMap);

		}

	}

	/**
	 * @param request
	 * @param response
	 * @return  教师批阅点击是ajax请求表单提交(前台传课程号，学生id)
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/isExamSource", method = RequestMethod.POST)
	public void isExamSource(String jsonStr, HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//返回字符串
		String reJsonStr = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//成功失败标识
		String resultMark = "fail";
		try {
			logger.info("教师批阅点击是ajax请求表单提交(前台传课程号，学生id)的参数为："+jsonStr);
			//获取参数值
			Map<String,Object> paramMap = mapper.readValue(jsonStr, resultMap.getClass());
			//将填空题、简答题错误个数和分数插入学生在线考试表考试总分数插入考试表中
			Map<String,Object> returnMap = questionActionImpl.addExameSource(paramMap,session,request);
			resultMap.put("resultMark", returnMap.get("resultMark"));
			resultMap.put("errMsg", returnMap.get("errMsg"));

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(" 教师批阅点击是ajax请求表单提交(前台传课程号，学生id)出现异常", e);
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			logger.info("教师批阅点击是ajax请求表单提交(前台传课程号，学生id)的返回结果为："+resultMap);
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter write = response.getWriter();
			write.println(reJsonStr);
			write.flush();
		}
	}

	/**
	 *
	 * @return  生成试题--获取教师所属课程列表页面。进页面，翻页，条件查询都是这个。
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getAllCourseListByTeaIdPost", method = RequestMethod.POST)
	public void getAllCourseListByTeaIdPost(String jsonStr,HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//返回字符串
		String reJsonStr = "";
		//存放页面
		String pageName = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();

		try {
			returnMap = mapper.readValue(jsonStr, returnMap.getClass());
			//获取题库列表信息
			Map<String, Object> resultAllMap = questionActionImpl.getAllCourseListByTeaIdPost(returnMap,request);
			String[] keysArray = {"tomcatUrl", "project_name","server_address"};
			Map<String, Object> urlmap = ConfigFileUtil.getFileMessage("UtilFile.properties", keysArray);
			//判断文件夹存不存在,不存在就创建
			String url = (String)urlmap.get("server_address")+(String)urlmap.get("project_name")+"upload/question"+"/";
			//返回值
			resultMap.put("courseList", resultAllMap.get("courseList"));
			resultMap.put("url",url);//下载路径
			resultMap.put("stuorteaId", resultAllMap.get("stuorteaId"));
			resultMap.put("result", "success");
			resultMap.put("failMsg", "");
		} catch (Exception e) {
			resultMap.put("result", "fail");
			resultMap.put("failMsg", "跳转页面失败");
			e.printStackTrace();
			logger.error("生成试题--获取教师所属课程列表页面出现异常", e);
		} finally {
			logger.info("题库列表页面的返回结果为："+resultMap);
			PubMethods.postMed(response,mapper,resultMap);
		}
	}

	/**
	 * @param request
	 * @param response
	 * @return  删除试卷,传回试卷id集合。List<String>形式   jsonStr = ["1","2"...]
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/delOnlineQuestion", method = RequestMethod.POST)
	public void delOnlineQuestion(String jsonStr, HttpServletRequest request, HttpServletResponse response) throws IOException {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//返回字符串
		String reJsonStr = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();

		//成功失败标识
		String resultMark = "fail";
		//用于转换参数
		List<String> list = new ArrayList<String>();
		try {

			logger.info("删除试卷的参数为："+jsonStr);
			//获取参数值
			List<String> paramList = mapper.readValue(jsonStr, list.getClass());
			//删除人员
			Map<String,Object> returnMap = questionActionImpl.delOnlineQuestion(paramList);
			boolean flag = (Boolean) returnMap.get("resultFlag");
			resultMark = (flag == true) ? "success" : "fail";
			resultMap.put("result", resultMark);
			resultMap.put("msg", returnMap.get("msg"));

		} catch (Exception e) {
			e.printStackTrace();
			logger.error("删除试卷出现异常", e);
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			logger.info("删除试卷的返回结果为："+resultMap);
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter write = response.getWriter();
			write.println(reJsonStr);
			write.flush();
		}
	}

	/**
	 * @param request
	 * @param response
	 * @return  获取当前教师所教的所有班级
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getAllClassByTeaId", method = RequestMethod.POST)
	public void getAllClassByTeaId(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//返回字符串
		String reJsonStr = "";
		//存放页面
		String pageName = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//成功失败标识
		String resultMark = "fail";
		Map<String, Object> paramMap = new HashMap<String, Object>();
		try {
			//获取当前登陆人的学号/工号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
			String stuorteaId = String.valueOf(sessionMap.get("stuorteaId"));
			paramMap.put("stuorteaId",stuorteaId);
			//获取当前教师所教的所有班级
			List<Map<String,Object>> classList = relStuClassActionImpl.getClassByStuorteaIdAndNo(paramMap);
			resultMap.put("classList",classList);

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(" 获取当前教师所教的所有班级出现异常", e);

		} finally {
			logger.info("获取当前教师所教的所有班级的返回结果为："+resultMap);
			PubMethods.postMed(response,mapper,resultMap);

		}

	}

	/**
	 * @param request
	 * @param response 试卷主键 onlinequestionId,courseId
	 * @return  教师点击开始考试
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/startExame", method = RequestMethod.POST)
	public void startExame(String jsonStr, HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();

		//返回字符串
		String reJsonStr = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		try {
			Map<String,Object> paramMap = new HashMap<String,Object>();
			paramMap = mapper.readValue(jsonStr, paramMap.getClass());
			//获取当前时间
			String nowTime = PubMethods.getNowTime(new Date(),1);
			//将已经考试状态和当前时间插入到数据库Onlinequestion表中za
			paramMap.put("starttime",nowTime);
			paramMap.put("examState",1);
			resultMap = questionActionImpl.updateOnlineState(paramMap,request);
			/*boolean falg = (Boolean)resultMap.get("resultFlag");
			String result = falg ==true?"success":"error";
			resultMap.put("result",result);*/
			resultMap.put("msg",resultMap.get("msg"));

		} catch (Exception e) {
			e.printStackTrace();
			logger.error("教师点击开始考试提交出现异常", e);
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			logger.info("教师点击开始考试提交的结果为："+reJsonStr);
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter write = response.getWriter();
			write.println(reJsonStr);
			write.flush();
		}
	}

	/**
	 * @param courseId
	 * @param request
	 * @param response
	 * @return  获取当前教师所教的所有班级及班级的考试状态详情
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getAllClassStateByTeaId", method = RequestMethod.POST)
	public void getAllClassStateByTeaId(String jsonStr,HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		try {
			paramMap = mapper.readValue(jsonStr, paramMap.getClass());
			//获取当前登陆人的学号/工号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
			String stuorteaId = String.valueOf(sessionMap.get("stuorteaId"));
			paramMap.put("stuorteaId",stuorteaId);
			//获取当前教师所教的所有班级
			Map<String, Object> returnMap = relStuClassActionImpl.getAllClassStateByTeaId(paramMap,request);
			List<Map<String,Object>> classList = (List<Map<String, Object>>) returnMap.get("finalList");
			resultMap.put("classList",classList);
			resultMap.put("endTime",returnMap.get("endTime"));
			resultMap.put("result","success");
			resultMap.put("failMsg","");
		} catch (Exception e) {
			resultMap.put("result","fail");
			resultMap.put("failMsg","获取当前教师所教的所有班级出现异常");
			e.printStackTrace();
			logger.error(" 获取当前教师所教的所有班级出现异常", e);

		} finally {
			logger.info("获取当前教师所教的所有班级的返回结果为："+resultMap);
			PubMethods.postMed(response,mapper,resultMap);

		}

	}

	/**
	 * @param request
	 * @param response
	 * @return  获取当前课程当前教师所拥有的试卷
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getTestPaperByCouId", method = RequestMethod.POST)
	public void getTestPaperByCouId(String jsonStr,HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		try {
			paramMap = mapper.readValue(jsonStr, paramMap.getClass());
			//获取当前登陆人的学号/工号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
			String stuorteaId = String.valueOf(sessionMap.get("stuorteaId"));
			paramMap.put("stuorteaId",stuorteaId);
			//获取当前教师的试卷列表
			List<Map<String,Object>> testPaperList = relStuClassActionImpl.getTestPaperByCouId(paramMap);
			resultMap.put("testPaperList",testPaperList);
			String[] keysArray = {"tomcatUrl", "project_name","server_address"};
			Map<String, Object> urlmap = ConfigFileUtil.getFileMessage("UtilFile.properties", keysArray);
			//判断文件夹存不存在,不存在就创建
			String url = String.valueOf(urlmap.get("server_address"))+String.valueOf(urlmap.get("project_name"))+"upload/question"+"/";
			resultMap.put("url",url);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(" 获取当前课程当前教师所拥有的试卷出现异常", e);

		} finally {
			logger.info("获取当前课程当前教师所拥有的试卷的返回结果为："+resultMap);
			PubMethods.postMed(response,mapper,resultMap);

		}

	}
}
